<template>
  <div class="order-confirmation">
    <!-- Business Header Section -->
    <div class="business-header" v-if="business">
      <div class="business-info-container">
        <img :src="business.head" alt="Business Logo" class="business-logo">
        <div class="business-details">
          <h2 class="business-name">{{ business.businessName }}</h2>
          <p class="business-address">
            <el-icon><Location /></el-icon>
            {{ business.address }}
          </p>
        </div>
      </div>
    </div>

    <!-- Shipping Address Section -->
    <div class="shipping-address">
      <h3 class="section-title">配送地址</h3>
      <template v-if="addressServiceAvailable">
        <el-radio-group v-model="selectedAddressId" class="address-list">
          <div v-for="address in shipmentAddresses" :key="address.id" class="address-item">
            <el-radio :value="address.id" class="address-radio">
              <div class="address-details">
                <div class="address-header">
                  <span class="user-name">{{ address.userName }}</span>
                  <span class="user-gender">{{ address.gender === 1 ? '先生' : '女士' }}</span>
                  <span class="user-phone">{{ address.phone }}</span>
                </div>
                <div class="address-content">
                  {{ address.address }}
                </div>
              </div>
            </el-radio>
          </div>
        </el-radio-group>
        <el-button class="add-address-btn" @click="showAddAddressDialog = true">
          <el-icon><Plus /></el-icon>添加新地址
        </el-button>
      </template>
      <template v-else>
        <div class="service-degradation">
          <el-alert
              title="地址服务暂时不可用"
              type="warning"
              :closable="false"
              show-icon
          >
            <p>请手动输入您的配送信息</p>
          </el-alert>
          <el-form class="fallback-address-form">
            <el-form-item label="收货人姓名">
              <el-input v-model="fallbackAddress.userName" placeholder="请输入收货人姓名"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="fallbackAddress.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input
                  v-model="fallbackAddress.address"
                  type="textarea"
                  placeholder="请输入详细地址"
                  :rows="3"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </div>

    <!-- Order Items Section -->
    <div class="order-items">
      <h3 class="section-title">订单详情</h3>
      <div class="items-list">
        <div v-for="item in orderItems" :key="item.foodId" class="order-item">
          <img :src="item.foodImage"
               alt="Food Image"
               class="item-image">
          <div class="item-info">
            <h4 class="item-name">{{ item.foodName }}</h4>
            <p class="item-price">¥{{ item.foodPrice.toFixed(2) }}</p>
          </div>
          <div class="item-quantity">
            ×{{ item.quantity }}
          </div>
          <div class="item-total">
            ¥{{ (item.foodPrice * item.quantity).toFixed(2) }}
          </div>
        </div>
      </div>
    </div>

    <!-- Order Summary Section -->
    <div class="order-summary">
      <div class="summary-row">
        <span class="label">商品总价</span>
        <span class="value">¥{{ orderTotal.toFixed(2) }}</span>
      </div>
      <div class="summary-row">
        <span class="label">配送费</span>
        <span class="value">¥0.00</span>
      </div>
      <div class="summary-row total">
        <span class="label">实付</span>
        <span class="value">¥{{ orderTotal.toFixed(2) }}</span>
      </div>
    </div>

    <!-- Server Busy Warning -->
    <div v-if="orderServiceUnavailable" class="server-busy-warning">
      <el-alert
          title="服务器繁忙，请稍后再试"
          type="error"
          :closable="false"
          show-icon
      />
    </div>

    <!-- Payment Button -->
    <div class="payment-button-container">
      <el-button
          type="success"
          class="payment-button"
          @click="proceedToPayment"
          :loading="isProcessing"
          :disabled="!canProceedToPayment || orderServiceUnavailable"
      >
        确认支付
      </el-button>
    </div>

    <!-- Add Address Dialog -->
    <el-dialog v-model="showAddAddressDialog" title="添加新地址" width="90%" :close-on-click-modal="false">
      <el-form :model="newAddress" label-width="80px" label-position="top">
        <el-form-item label="姓名">
          <el-input v-model="newAddress.userName" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="newAddress.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="newAddress.gender">
            <el-radio :value="1">先生</el-radio>
            <el-radio :value="0">女士</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input
              v-model="newAddress.address"
              type="textarea"
              placeholder="请输入详细地址"
              :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddAddressDialog = false">取消</el-button>
        <el-button type="primary" @click="saveNewAddress">保存</el-button>
      </template>
    </el-dialog>

    <!-- Service Degradation Notification -->
    <el-dialog
        v-model="showServiceDegradationNotice"
        title="服务提示"
        width="90%"
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="false"
    >
      <div class="degradation-notice">
        <el-alert
            title="部分服务暂时不可用"
            type="warning"
            :closable="false"
            show-icon
        >
          <p>当前地址服务不可用，系统已启用降级方案，您仍可继续下单。</p>
          <p>部分功能可能受限，请稍后再试。</p>
        </el-alert>
      </div>
      <template #footer>
        <el-button type="primary" @click="showServiceDegradationNotice = false">我知道了</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Location, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const business = ref(null)
const orderItems = ref([])
const orderTotal = ref(0)
const isProcessing = ref(false)
const shipmentAddresses = ref([])
const selectedAddressId = ref(null)
const showAddAddressDialog = ref(false)
const addressServiceAvailable = ref(true) // 默认服务可用
const showServiceDegradationNotice = ref(false)
const orderServiceUnavailable = ref(false) // 订单服务是否可用

// 降级方案中的地址表单
const fallbackAddress = ref({
  userName: '',
  phone: '',
  address: ''
})

const newAddress = ref({
  userName: '',
  phone: '',
  address: '',
  gender: 1
})

// 计算属性，检查是否可以继续支付
const canProceedToPayment = computed(() => {
  if (addressServiceAvailable.value) {
    return !!selectedAddressId.value
  } else {
    return !!fallbackAddress.value.userName &&
        !!fallbackAddress.value.phone &&
        !!fallbackAddress.value.address
  }
})

// Load order data and check services availability
const loadOrderData = async () => {
  try {
    const orderData = JSON.parse(localStorage.getItem('pendingOrder'))
    if (!orderData) {
      throw new Error('未找到订单数据')
    }

    business.value = orderData.business
    orderItems.value = orderData.orderItems
    orderTotal.value = orderData.totalAmount

    const token = localStorage.getItem('access_token')
    if (!token) {
      throw new Error('未找到访问令牌')
    }

    // 尝试加载地址数据 - 如果失败则地址服务不可用
    try {
      const [addressResponse] = await Promise.all([
        fetch(`http://localhost:8080/shipment/list/${orderData.wechatId}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }),
        // 同时检查订单服务
      ]);

      if (!addressResponse.ok) {
        throw new Error('地址服务不可用')
      }

      shipmentAddresses.value = await addressResponse.json()

      // 如果有地址，默认选择第一个
      if (shipmentAddresses.value.length > 0) {
        selectedAddressId.value = shipmentAddresses.value[0].id
      }
    } catch (addressError) {
      console.error('地址服务加载失败:', addressError)
      addressServiceAvailable.value = false
      showServiceDegradationNotice.value = true
    }

    // // 检查订单服务是否可用
    // try {
    //   const orderHealthResponse = await fetch('http://localhost:8080/order/actuator/health', {
    //     method: 'GET',
    //     headers: {
    //       'Authorization': `Bearer ${token}`,
    //       'Content-Type': 'application/json'
    //     }
    //   })
    //
    //   if (!orderHealthResponse.ok || (await orderHealthResponse.json()).status !== 'UP') {
    //     throw new Error('订单服务不可用')
    //   }
    // } catch (orderError) {
    //   console.error('订单服务检查失败:', orderError)
    //   orderServiceUnavailable.value = true
    // }

  } catch (error) {
    console.error('加载订单数据错误:', error)
    ElMessage.error('加载订单信息失败: ' + error.message)

    // 如果订单数据加载失败，重定向回首页
    if (error.message.includes('未找到订单数据')) {
      window.location.href = '/'
    }

    // 其他情况启用降级方案
    addressServiceAvailable.value = false
    showServiceDegradationNotice.value = true
  }
}

// Save new address
const saveNewAddress = async () => {
  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      throw new Error('未找到访问令牌')
    }

    const orderData = JSON.parse(localStorage.getItem('pendingOrder'))
    const addressData = {
      ...newAddress.value,
      wechatId: orderData.wechatId
    }

    const response = await fetch('http://localhost:8080/shipment/insert', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(addressData)
    })

    if (!response.ok) {
      throw new Error(`HTTP错误! 状态码: ${response.status}`)
    }

    const result = await response.json()
    if (result) {
      ElMessage.success('地址添加成功')
      showAddAddressDialog.value = false
      // 重新加载地址
      await loadShipmentAddresses(orderData.wechatId)
      // 选择新地址
      selectedAddressId.value = result.id
    } else {
      throw new Error('地址添加失败')
    }
  } catch (error) {
    console.error('保存地址错误:', error)
    ElMessage.error('地址添加失败: ' + error.message)
  }
}

// Proceed to payment
const proceedToPayment = async () => {
  try {
    isProcessing.value = true

    const token = localStorage.getItem('access_token')
    if (!token) {
      throw new Error('未找到访问令牌')
    }

    const orderData = JSON.parse(localStorage.getItem('pendingOrder'))
    if (!orderData) {
      throw new Error('订单数据丢失，请重新下单')
    }

    if (orderServiceUnavailable.value) {
      throw new Error('订单服务暂时不可用，请稍后再试')
    }

    // 准备订单项数据
    const orderItemsForBackend = orderData.orderItems.map(item => ({
      foodId: item.foodId,
      quantity: item.quantity
    }))

    let addressInfo = {}
    if (addressServiceAvailable.value) {
      // 使用正常地址服务
      const selectedAddress = shipmentAddresses.value.find(addr => addr.id === selectedAddressId.value)
      if (!selectedAddress) {
        throw new Error('请选择配送地址')
      }
      addressInfo = {
        phone: selectedAddress.phone,
        address: selectedAddress.address
      }
    } else {
      // 使用降级方案的地址
      if (!fallbackAddress.value.userName || !fallbackAddress.value.phone || !fallbackAddress.value.address) {
        throw new Error('请填写完整的配送信息')
      }
      addressInfo = {
        phone: fallbackAddress.value.phone,
        address: `${fallbackAddress.value.userName} ${fallbackAddress.value.phone} ${fallbackAddress.value.address}`
      }
    }

    // 创建请求负载
    const requestPayload = {
      businessId: orderData.business.businessId,
      wechatId: orderData.wechatId,
      phone: addressInfo.phone,
      note: addressServiceAvailable.value ? '' : '使用降级方案地址',
      address: addressInfo.address,
      orderRows: orderItemsForBackend
    }

    try {
      const response = await fetch('http://localhost:8080/order/create', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestPayload)
      })

      if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`)
      }

      const result = await response.json()
      if (result) {
        localStorage.removeItem('pendingOrder')
        ElMessage.success('订单提交成功')
        window.location.href = '/'
      } else {
        throw new Error('订单提交失败')
      }
    } catch (orderError) {
      console.error('订单提交错误:', orderError)
      await fallbackOrderSubmission(requestPayload)
    }
  } catch (error) {
    console.error('支付处理错误:', error)
    ElMessage.error('订单提交失败: ' + error.message)
  } finally {
    isProcessing.value = false
  }
}

// 降级订单提交方案
const fallbackOrderSubmission = async (orderData) => {
  try {
    const pendingOrders = JSON.parse(localStorage.getItem('pendingOfflineOrders') || '[]')
    pendingOrders.push({
      ...orderData,
      timestamp: new Date().toISOString(),
      status: 'pending'
    })
    localStorage.setItem('pendingOfflineOrders', JSON.stringify(pendingOrders))

    localStorage.removeItem('pendingOrder')

    ElMessage.success('订单已保存，将在服务恢复后自动提交')
    window.location.href = '/'
  } catch (error) {
    console.error('降级订单保存失败:', error)
    throw new Error('无法保存订单，请稍后再试')
  }
}

onMounted(() => {
  loadOrderData()
})
</script>

<style scoped>
.order-confirmation {
  max-width: 800px;
  margin: 0 auto;
  padding: 15px;
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 100px;
}

.business-header {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.business-info-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.business-logo {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.business-details {
  flex: 1;
}

.business-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.business-address {
  margin: 0;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* Shipping address styles */
.shipping-address {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  padding: 12px;
  border-radius: 8px;
  background-color: #f9f9f9;
  border: 1px solid #eee;
  width: 80%;
}

.address-radio {
  width: 100%;
}

.address-details {
  margin-left: 10px;
}

.address-header {
  margin-bottom: 5px;
  font-size: 15px;
}

.user-name {
  font-weight: bold;
  margin-right: 8px;
}

.user-gender {
  margin-right: 15px;
  color: #666;
}

.user-phone {
  color: #666;
}

.address-content {
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.add-address-btn {
  width: 100%;
  margin-top: 10px;
  color: #409eff;
}

/* Service degradation styles */
.service-degradation {
  margin-top: 15px;
}

.fallback-address-form {
  margin-top: 20px;
}

.degradation-notice {
  margin-bottom: 20px;
}

/* Server busy warning */
.server-busy-warning {
  margin-bottom: 15px;
}

/* Order items styles */
.order-items {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 15px 0;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 3px;
  height: 14px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 8px;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 15px;
}

.item-info {
  flex: 1;
}

.item-name {
  margin: 0 0 5px 0;
  font-size: 15px;
  color: #333;
}

.item-price {
  margin: 0;
  font-size: 14px;
  color: #999;
}

.item-quantity {
  width: 50px;
  text-align: center;
  font-size: 15px;
  color: #666;
}

.item-total {
  width: 80px;
  text-align: right;
  font-size: 15px;
  font-weight: bold;
  color: #f56c6c;
}

/* Order summary styles */
.order-summary {
  background-color: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 15px;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-row.total {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.label {
  color: #666;
}

.value {
  color: #333;
}

/* Payment button styles */
.payment-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.payment-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

@media (max-width: 480px) {
  .business-logo {
    width: 70px;
    height: 70px;
  }

  .business-name {
    font-size: 16px;
  }

  .business-address {
    font-size: 13px;
  }

  .item-image {
    width: 50px;
    height: 50px;
  }

  .item-name {
    font-size: 14px;
  }

  .item-price, .item-quantity, .item-total {
    font-size: 13px;
  }

  .summary-row {
    font-size: 14px;
  }

  .summary-row.total {
    font-size: 15px;
  }
}

@media (min-width: 600px) {
  .business-logo {
    width: 90px;
    height: 90px;
  }

  .business-name {
    font-size: 20px;
  }

  .business-address {
    font-size: 15px;
  }

  .item-image {
    width: 70px;
    height: 70px;
  }

  .item-name {
    font-size: 16px;
  }

  .item-price, .item-quantity, .item-total {
    font-size: 15px;
  }

  .summary-row {
    font-size: 16px;
  }

  .summary-row.total {
    font-size: 18px;
  }
}
</style>